﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint;
using ClaimsScaffold.Claims;
using Microsoft.SharePoint.Administration.Claims;

namespace ClaimsAugScaffoldConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //the first argument should be the url to a sharepoint web
                string siteUrl = args[0];

                using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        Console.WriteLine(string.Format("Connection to web at {0} successful.  Proceeding with assignment of custom claim value of {1}."), siteUrl, ClaimProvider.TEST_CLAIM_VALUE);
                        SPClaim claim = ClaimProvider.CreateClaim(ClaimProvider.CLAIM_TYPE, ClaimProvider.TEST_CLAIM_VALUE);
                        string encoded = claim.ToEncodedString();
                        SPRoleAssignment assignment = new SPRoleAssignment(encoded, null, claim.Value, null);
                        SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                        assignment.RoleDefinitionBindings.Add(roleDef);
                        if (!web.HasUniqueRoleAssignments)
                        {
                            web.BreakRoleInheritance(false);
                        }
                        web.RoleAssignments.Add(assignment);
                        web.Update();
                        Console.WriteLine(string.Format("Claims assginment successful.  Once the custom claim provider is activated, users authenticating to the site will be granted the claim and should have contribute access to the web at {0}.", siteUrl));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}
